package com.wyj.utils

import android.graphics.*
import android.graphics.Bitmap.CompressFormat
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.core.graphics.drawable.toBitmap
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream


object BitmapUtils {
    @JvmStatic
    fun byte2InputStream(b: ByteArray?): InputStream? = b?.let { ByteArrayInputStream(it) }

    // 将InputStream转换成byte[]
    @JvmStatic
    fun inputStream2Bytes(inputStream: InputStream): ByteArray? {
        val swapStream = ByteArrayOutputStream()
        val buff = ByteArray(1024)
        var rc = 0
        while (inputStream.read(buff, 0, 1024).also { rc = it } > 0) {
            swapStream.write(buff, 0, rc)
        }
        return swapStream.toByteArray()
    }


    // 将Bitmap转换成InputStream
    @JvmStatic
    @JvmOverloads
    fun bitmap2InputStream(bm: Bitmap, quality: Int = 100): InputStream = ByteArrayInputStream(this.bitmap2Bytes(bm, quality))

    // 将InputStream转换成Bitmap
    @JvmStatic
    fun inputStream2Bitmap(inputStream: InputStream): Bitmap = BitmapFactory.decodeStream(inputStream)

    // Drawable转换成InputStream
    @JvmStatic
    fun drawable2InputStream(d: Drawable): InputStream = this.bitmap2InputStream(drawable2Bitmap(d))

    // InputStream转换成Drawable
    @JvmStatic
    fun inputStream2Drawable(inputStream: InputStream): Drawable? = this.bitmap2Drawable(inputStream2Bitmap(inputStream))

    // Drawable转换成byte[]
    @JvmStatic
    fun drawable2Bytes(d: Drawable?): ByteArray? = d?.let { bitmap2Bytes(drawable2Bitmap(it)) }

    // byte[]转换成Drawable
    @JvmStatic
    fun bytes2Drawable(b: ByteArray?): Drawable? = b?.let { bitmap2Drawable(bytes2Bitmap(it)) }

    // Bitmap转换成byte[]
    @JvmStatic
    @JvmOverloads
    fun bitmap2Bytes(bm: Bitmap, quality: Int = 100): ByteArray = ByteArrayOutputStream().let {
        bm.compress(CompressFormat.PNG, quality, it)
        it.toByteArray()
    }

    // byte[]转换成Bitmap
    @JvmStatic
    fun bytes2Bitmap(b: ByteArray): Bitmap? = if (b.isNotEmpty()) BitmapFactory.decodeByteArray(b, 0, b.size) else null


    // Drawable转换成Bitmap
    @JvmStatic
    fun drawable2Bitmap(drawable: Drawable): Bitmap = drawable.toBitmap()

    // Bitmap转换成Drawable
    @JvmStatic
    fun bitmap2Drawable(bitmap: Bitmap?): Drawable? = bitmap?.let { BitmapDrawable(it) }
}
